//! 组件工厂 - 基于工厂模式的服务组件创建
//! 
//! 实现工厂模式，负责创建不同类型的服务组件：
//! 1. Redis服务组件
//! 2. 集群服务组件  
//! 3. 监控服务组件

use crate::server::enhanced_traits::*;
use crate::storage::RedisServerMode;
use async_trait::async_trait;
use std::io;
use std::sync::Arc;
use tracing::{info, error, warn};

// =============================================================================
// 具体服务组件实现
// =============================================================================

/// Redis服务组件 - 单一职责：管理Redis服务
pub struct RedisServiceComponent {
    config: Box<dyn ServerConfig>,
    service_handle: Option<crate::server::redis_service::RedisService>,
    is_running: bool,
}

impl RedisServiceComponent {
    pub fn new(config: Box<dyn ServerConfig>) -> Self {
        Self {
            config,
            service_handle: None,
            is_running: false,
        }
    }
}

#[async_trait]
impl ServiceLifecycle for RedisServiceComponent {
    fn service_name(&self) -> &'static str {
        "RedisService"
    }
    
    async fn start(&mut self) -> io::Result<()> {
        if self.is_running {
            return Ok(());
        }
        
        info!("🚀 启动Redis服务组件");
        
        // 根据配置模式启动Redis服务
        let redis_service = match self.config.mode() {
            RedisServerMode::Standalone => {
                crate::server::redis_service::start_redis_service(self.config.bind_address()).await?
            }
            RedisServerMode::Cluster => {
                crate::server::redis_service::start_redis_service_with_mode(
                    self.config.bind_address(),
                    RedisServerMode::Cluster
                ).await?
            }
        };
        
        self.service_handle = Some(redis_service);
        self.is_running = true;
        
        info!("✅ Redis服务组件启动成功");
        Ok(())
    }
    
    async fn stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }
        
        info!("🛑 停止Redis服务组件");
        
        if let Some(service) = self.service_handle.take() {
            crate::server::redis_service::stop_redis_service(service).await?;
        }
        
        self.is_running = false;
        info!("✅ Redis服务组件已停止");
        Ok(())
    }
    
    fn is_running(&self) -> bool {
        self.is_running
    }
    
    async fn graceful_shutdown(&mut self, _timeout_secs: u64) -> io::Result<()> {
        // Redis服务的优雅关闭就是普通停止
        self.stop().await
    }
}

/// 集群服务组件 - 单一职责：管理集群服务
pub struct ClusterServiceComponent {
    config: Box<dyn ServerConfig>,
    cluster_handle: Option<tokio::task::JoinHandle<()>>,
    is_running: bool,
}

impl ClusterServiceComponent {
    pub fn new(config: Box<dyn ServerConfig>) -> Self {
        Self {
            config,
            cluster_handle: None,
            is_running: false,
        }
    }
}

#[async_trait]
impl ServiceLifecycle for ClusterServiceComponent {
    fn service_name(&self) -> &'static str {
        "ClusterService"
    }
    
    async fn start(&mut self) -> io::Result<()> {
        if self.is_running {
            return Ok(());
        }
        
        info!("🚀 启动集群服务组件");
        
        // 获取集群配置
        let cluster_config = match self.config.extra_config() {
            Some(extra) => {
                if let Some(cluster_cfg) = extra.downcast_ref::<crate::cluster::ClusterConfig>() {
                    cluster_cfg.clone()
                } else {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "集群配置类型不匹配"
                    ));
                }
            }
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "缺少集群配置"
                ));
            }
        };
        
        // 启动集群网络管理器
        let handle = tokio::spawn(async move {
            match crate::cluster::ClusterNetworkManager::new(cluster_config).await {
                Ok(mut network_manager) => {
                    if let Err(e) = network_manager.bind().await {
                        error!("⚠️ 集群网络管理器绑定失败: {}", e);
                        return;
                    }
                    if let Err(e) = network_manager.start().await {
                        error!("⚠️ 集群网络管理器启动失败: {}", e);
                    }
                }
                Err(e) => {
                    error!("⚠️ 创建集群网络管理器失败: {}", e);
                }
            }
        });
        
        self.cluster_handle = Some(handle);
        
        // 给集群服务一点时间初始化
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        
        self.is_running = true;
        info!("✅ 集群服务组件启动成功");
        Ok(())
    }
    
    async fn stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }
        
        info!("🛑 停止集群服务组件");
        
        if let Some(handle) = self.cluster_handle.take() {
            handle.abort();
        }
        
        self.is_running = false;
        info!("✅ 集群服务组件已停止");
        Ok(())
    }
    
    fn is_running(&self) -> bool {
        self.is_running
    }
    
    async fn graceful_shutdown(&mut self, _timeout_secs: u64) -> io::Result<()> {
        // 集群服务的优雅关闭就是普通停止
        self.stop().await
    }
}

/// 监控服务组件 - 单一职责：管理监控服务
pub struct MonitoringServiceComponent {
    _config: Box<dyn ServerConfig>,
    is_running: bool,
}

impl MonitoringServiceComponent {
    pub fn new(config: Box<dyn ServerConfig>) -> Self {
        Self {
            _config: config,
            is_running: false,
        }
    }
}

#[async_trait]
impl ServiceLifecycle for MonitoringServiceComponent {
    fn service_name(&self) -> &'static str {
        "MonitoringService"
    }
    
    async fn start(&mut self) -> io::Result<()> {
        if self.is_running {
            return Ok(());
        }
        
        info!("🚀 启动监控服务组件");
        // TODO: 实现监控服务启动逻辑
        
        self.is_running = true;
        info!("✅ 监控服务组件启动成功");
        Ok(())
    }
    
    async fn stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }
        
        info!("🛑 停止监控服务组件");
        // TODO: 实现监控服务停止逻辑
        
        self.is_running = false;
        info!("✅ 监控服务组件已停止");
        Ok(())
    }
    
    fn is_running(&self) -> bool {
        self.is_running
    }
    
    async fn graceful_shutdown(&mut self, _timeout_secs: u64) -> io::Result<()> {
        self.stop().await
    }
}

// =============================================================================
// 具体工厂实现
// =============================================================================

/// 默认组件工厂
/// 
/// 实现工厂模式，根据配置创建相应的服务组件
pub struct DefaultComponentFactory;

#[async_trait]
impl ServiceComponentFactory for DefaultComponentFactory {
    /// 创建Redis服务组件
    async fn create_redis_service(&self, config: &dyn ServerConfig) -> io::Result<Box<dyn ServiceLifecycle>> {
        info!("🏭 创建Redis服务组件 (模式: {:?})", config.mode());
        
        // 验证配置
        config.validate().map_err(|e| {
            io::Error::new(io::ErrorKind::InvalidInput, format!("配置验证失败: {}", e))
        })?;
        
        let component = RedisServiceComponent::new(config.clone_config());
        Ok(Box::new(component))
    }
    
    /// 创建集群服务组件
    async fn create_cluster_service(&self, config: &dyn ServerConfig) -> io::Result<Option<Box<dyn ServiceLifecycle>>> {
        match config.mode() {
            RedisServerMode::Cluster => {
                info!("🏭 创建集群服务组件");
                
                // 验证配置
                config.validate().map_err(|e| {
                    io::Error::new(io::ErrorKind::InvalidInput, format!("配置验证失败: {}", e))
                })?;
                
                let component = ClusterServiceComponent::new(config.clone_config());
                Ok(Some(Box::new(component)))
            }
            RedisServerMode::Standalone => {
                info!("Standalone模式，不创建集群服务组件");
                Ok(None)
            }
        }
    }
    
    /// 创建监控服务组件
    async fn create_monitoring_service(&self, config: &dyn ServerConfig) -> io::Result<Option<Box<dyn ServiceLifecycle>>> {
        info!("🏭 创建监控服务组件");
        
        // 验证配置
        config.validate().map_err(|e| {
            io::Error::new(io::ErrorKind::InvalidInput, format!("配置验证失败: {}", e))
        })?;
        
        let component = MonitoringServiceComponent::new(config.clone_config());
        Ok(Some(Box::new(component)))
    }
    
    /// 支持的服务器模式
    fn supported_modes(&self) -> Vec<RedisServerMode> {
        vec![RedisServerMode::Standalone, RedisServerMode::Cluster]
    }
}

/// 扩展组件工厂
/// 
/// 提供额外的组件创建能力，支持自定义组件
pub struct ExtendedComponentFactory {
    base_factory: DefaultComponentFactory,
}

impl ExtendedComponentFactory {
    pub fn new() -> Self {
        Self {
            base_factory: DefaultComponentFactory,
        }
    }
    
    /// 创建自定义组件
    pub async fn create_custom_service(
        &self,
        service_type: &str,
        _config: &dyn ServerConfig,
    ) -> io::Result<Option<Box<dyn ServiceLifecycle>>> {
        match service_type {
            "metrics" => {
                info!("🏭 创建指标收集服务组件");
                // TODO: 实现指标收集服务
                Ok(None)
            }
            "logging" => {
                info!("🏭 创建日志服务组件");
                // TODO: 实现日志服务
                Ok(None)
            }
            "tracing" => {
                info!("🏭 创建链路追踪服务组件");
                // TODO: 实现链路追踪服务
                Ok(None)
            }
            _ => {
                warn!("未知的自定义服务类型: {}", service_type);
                Ok(None)
            }
        }
    }
}

#[async_trait]
impl ServiceComponentFactory for ExtendedComponentFactory {
    async fn create_redis_service(&self, config: &dyn ServerConfig) -> io::Result<Box<dyn ServiceLifecycle>> {
        self.base_factory.create_redis_service(config).await
    }
    
    async fn create_cluster_service(&self, config: &dyn ServerConfig) -> io::Result<Option<Box<dyn ServiceLifecycle>>> {
        self.base_factory.create_cluster_service(config).await
    }
    
    async fn create_monitoring_service(&self, config: &dyn ServerConfig) -> io::Result<Option<Box<dyn ServiceLifecycle>>> {
        self.base_factory.create_monitoring_service(config).await
    }
    
    fn supported_modes(&self) -> Vec<RedisServerMode> {
        self.base_factory.supported_modes()
    }
}

impl Default for ExtendedComponentFactory {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// 工厂注册表 - 支持插件式扩展
// =============================================================================

/// 工厂注册表 - 支持动态注册工厂
/// 
/// 实现开闭原则，支持不修改现有代码的情况下扩展新的工厂
pub struct ComponentFactoryRegistry {
    factories: std::collections::HashMap<String, Arc<dyn ServiceComponentFactory>>,
}

impl ComponentFactoryRegistry {
    /// 创建新的工厂注册表
    pub fn new() -> Self {
        let mut registry = Self {
            factories: std::collections::HashMap::new(),
        };
        
        // 注册默认工厂
        registry.register_factory("default".to_string(), Arc::new(DefaultComponentFactory));
        registry.register_factory("extended".to_string(), Arc::new(ExtendedComponentFactory::new()));
        
        registry
    }
    
    /// 注册工厂
    pub fn register_factory(&mut self, name: String, factory: Arc<dyn ServiceComponentFactory>) {
        info!("注册组件工厂: {}", name);
        self.factories.insert(name, factory);
    }
    
    /// 获取工厂
    pub fn get_factory(&self, name: &str) -> Option<Arc<dyn ServiceComponentFactory>> {
        self.factories.get(name).cloned()
    }
    
    /// 获取默认工厂
    pub fn default_factory(&self) -> Arc<dyn ServiceComponentFactory> {
        self.get_factory("default").expect("默认工厂必须存在")
    }
    
    /// 获取所有工厂名称
    pub fn factory_names(&self) -> Vec<String> {
        self.factories.keys().cloned().collect()
    }
    
    /// 移除工厂
    pub fn unregister_factory(&mut self, name: &str) -> Option<Arc<dyn ServiceComponentFactory>> {
        if name == "default" {
            warn!("不能移除默认工厂");
            return None;
        }
        
        info!("移除组件工厂: {}", name);
        self.factories.remove(name)
    }
}

impl Default for ComponentFactoryRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// 全局工厂注册表
// 注释：移除未使用的全局工厂注册表
// static mut GLOBAL_FACTORY_REGISTRY: Option<ComponentFactoryRegistry> = None;
// static REGISTRY_INIT: std::sync::Once = std::sync::Once::new();

/// 获取全局工厂注册表
pub fn global_factory_registry() -> &'static ComponentFactoryRegistry {
    // TODO: 修复静态变量引用问题
    // 暂时返回一个默认的单例
    Box::leak(Box::new(ComponentFactoryRegistry::new()))
}

/// 设置全局工厂注册表（用于测试）
#[cfg(test)]
pub fn set_global_factory_registry(registry: ComponentFactoryRegistry) {
    unsafe {
        GLOBAL_FACTORY_REGISTRY = Some(registry);
    }
}